<template>
  <div class="logistics-container">
    <h2 class="page-title">物流管理</h2>
    
    <el-tabs v-model="activeTab" class="logistics-tabs" type="border-card">
      <el-tab-pane label="物流单管理" name="shipments">
        <div class="filter-bar">
          <el-input 
            placeholder="搜索物流单号/订单号..." 
            prefix-icon="el-icon-search" 
            v-model="shipmentSearch" 
            class="search-input"
            clearable
          ></el-input>
          <el-select v-model="shipmentStatusFilter" placeholder="物流状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待处理" value="PENDING"></el-option>
            <el-option label="处理中" value="PROCESSING"></el-option>
            <el-option label="已发货" value="SHIPPED"></el-option>
            <el-option label="运输中" value="IN_TRANSIT"></el-option>
            <el-option label="派送中" value="OUT_FOR_DELIVERY"></el-option>
            <el-option label="已送达" value="DELIVERED"></el-option>
            <el-option label="异常" value="EXCEPTION"></el-option>
            <el-option label="已退回" value="RETURNED"></el-option>
            <el-option label="已取消" value="CANCELLED"></el-option>
          </el-select>
          <el-select v-model="carrierFilter" placeholder="承运商" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option v-for="carrier in carriers" :key="carrier.id" :label="carrier.name" :value="carrier.name"></el-option>
          </el-select>
          <el-date-picker 
            v-model="shipmentDateRange" 
            type="daterange" 
            range-separator="至" 
            start-placeholder="开始日期" 
            end-placeholder="结束日期"
            class="date-picker"
          ></el-date-picker>
        </div>
        
        <el-card shadow="hover" class="table-card">
          <el-table 
            :data="filteredShipments" 
            style="width: 100%" 
            border 
            v-loading="loading"
            stripe
            highlight-current-row
          >
            <el-table-column prop="trackingNumber" label="物流单号" width="160" sortable>
              <template #default="scope">
                <span class="tracking-number">{{ scope.row.trackingNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="orderId" label="订单编号" width="140" sortable></el-table-column>
            <el-table-column prop="carrierName" label="承运商" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getShipmentStatusType(scope.row.status)" effect="dark">
                  {{ getChineseShipmentStatus(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="shippingDate" label="发货日期" width="180" sortable></el-table-column> -->
            <el-table-column prop="estimatedDeliveryDate" label="预计送达" width="180" sortable></el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="scope">
                <el-button size="small" type="primary" @click="viewShipmentDetail(scope.row)" icon="el-icon-view">查看</el-button>
                <el-button size="small" type="success" @click="updateShipmentStatus(scope.row)" icon="el-icon-edit">更新状态</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalShipments"
              background>
            </el-pagination>
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="承运商管理" name="carriers">
        <div class="action-bar">
          <el-button type="primary" @click="showCarrierDialog(null)" icon="el-icon-plus">添加承运商</el-button>
        </div>
        
        <el-card shadow="hover" class="table-card">
          <el-table 
            :data="carriers" 
            style="width: 100%" 
            border 
            v-loading="loading"
            stripe
          >
            <el-table-column prop="name" label="承运商名称" width="150"></el-table-column>
            <el-table-column prop="code" label="承运商代码" width="120"></el-table-column>
            <el-table-column prop="contactPerson" label="联系人" width="120"></el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" width="150"></el-table-column>
            <el-table-column prop="supportedCountries" label="支持国家/地区" width="150">
              <template #default="scope">
                <el-tooltip placement="top" effect="light">
                  <template #content>
                    <div>{{ scope.row.supportedCountries }}</div>
                  </template>
                  <div class="ellipsis">{{ scope.row.supportedCountries }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="isActive" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isActive ? 'success' : 'info'" effect="dark">
                  {{ scope.row.isActive ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="250">
              <template #default="scope">
                <el-button size="small" type="primary" @click="showCarrierDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button size="small" :type="scope.row.isActive ? 'warning' : 'success'" @click="toggleCarrierStatus(scope.row)">
                  {{ scope.row.isActive ? '禁用' : '启用' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteCarrier(scope.row)" :disabled="scope.row.isActive" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 物流单详情对话框 -->
    <el-dialog
      title="物流单详情"
      v-model="shipmentDetailDialogVisible"
      width="700px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="物流单号">{{ currentShipment.trackingNumber }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{ currentShipment.orderId }}</el-descriptions-item>
        <el-descriptions-item label="承运商">{{ currentShipment.carrierName }}</el-descriptions-item>
        <el-descriptions-item label="物流方式">{{ currentShipment.shippingMethod }}</el-descriptions-item>
        <el-descriptions-item label="物流状态">
          <el-tag :type="getShipmentStatusType(currentShipment.status)" effect="dark">
            {{ getChineseShipmentStatus(currentShipment.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户ID">{{ currentShipment.customerId }}</el-descriptions-item>
        <el-descriptions-item label="发货日期" :span="2">{{ currentShipment.shippingDate }}</el-descriptions-item>
        <el-descriptions-item label="预计送达日期">{{ currentShipment.estimatedDeliveryDate }}</el-descriptions-item>
        <el-descriptions-item label="实际送达日期">{{ currentShipment.actualDeliveryDate || '未送达' }}</el-descriptions-item>
        <el-descriptions-item label="发货地址" :span="2">{{ currentShipment.originAddress }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentShipment.destinationAddress }}</el-descriptions-item>
        <el-descriptions-item label="包裹尺寸">{{ currentShipment.packageDimensions || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="包裹重量">{{ currentShipment.packageWeight ? currentShipment.packageWeight + 'kg' : '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentShipment.notes || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipmentDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="updateShipmentStatus(currentShipment)">更新状态</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 更新物流状态对话框 -->
    <el-dialog
      title="更新物流状态"
      v-model="updateStatusDialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="物流单号">{{ currentShipment.trackingNumber }}</el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getShipmentStatusType(currentShipment.status)" effect="dark">
            {{ getChineseShipmentStatus(currentShipment.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="选择新状态">
            <el-option label="待处理" value="PENDING"></el-option>
            <el-option label="处理中" value="PROCESSING"></el-option>
            <el-option label="已发货" value="SHIPPED"></el-option>
            <el-option label="运输中" value="IN_TRANSIT"></el-option>
            <el-option label="派送中" value="OUT_FOR_DELIVERY"></el-option>
            <el-option label="已送达" value="DELIVERED"></el-option>
            <el-option label="异常" value="EXCEPTION"></el-option>
            <el-option label="已退回" value="RETURNED"></el-option>
            <el-option label="已取消" value="CANCELLED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货日期" v-if="statusForm.status === 'SHIPPED'">
          <el-date-picker 
            v-model="statusForm.shippingDate" 
            type="datetime" 
            placeholder="选择发货日期时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="送达日期" v-if="statusForm.status === 'DELIVERED'">
          <el-date-picker 
            v-model="statusForm.deliveryDate" 
            type="datetime" 
            placeholder="选择送达日期时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateStatusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate" :loading="submitting">确认更新</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 承运商表单对话框 -->
    <el-dialog
      :title="isEdit ? '编辑承运商' : '添加承运商'"
      v-model="carrierDialogVisible"
      width="600px"
      destroy-on-close
    >
      <el-form :model="carrierForm" :rules="carrierRules" ref="carrierFormRef" label-width="120px">
        <el-form-item label="承运商名称" prop="name">
          <el-input v-model="carrierForm.name" placeholder="请输入承运商名称"></el-input>
        </el-form-item>
        <el-form-item label="承运商代码" prop="code">
          <el-input v-model="carrierForm.code" placeholder="请输入承运商代码"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="carrierForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="carrierForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="carrierForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
        </el-form-item>
        <el-form-item label="跟踪网址模板" prop="trackingUrlTemplate">
          <el-input v-model="carrierForm.trackingUrlTemplate" placeholder="请输入跟踪网址模板，使用{tracking_number}作为替换符"></el-input>
        </el-form-item>
        <el-form-item label="支持的国家/地区" prop="supportedCountries">
          <el-input v-model="carrierForm.supportedCountries" placeholder="请输入支持的国家/地区，多个用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="服务选项" prop="serviceOptions">
          <el-input v-model="carrierForm.serviceOptions" placeholder="请输入服务选项，多个用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="carrierForm.isActive" active-text="启用" inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="carrierDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCarrierForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import logisticsApi, { ShipmentStatus, IShipmentDto, ICarrierDto } from '../../api/logistics';

// 标签页
const activeTab = ref('shipments');

// 加载状态
const loading = ref(false);
const submitting = ref(false);

// 物流单相关
const shipments = ref([]);
const shipmentSearch = ref('');
const shipmentStatusFilter = ref('');
const carrierFilter = ref('');
const shipmentDateRange = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const totalShipments = ref(0);

// 物流单详情
const currentShipment = ref({});
const shipmentDetailDialogVisible = ref(false);
const updateStatusDialogVisible = ref(false);
const statusForm = reactive({
  status: '',
  shippingDate: null,
  deliveryDate: null
});

// 承运商相关
const carriers = ref([]);
const isEdit = ref(false);
const carrierDialogVisible = ref(false);
const carrierForm = reactive({
  id: null,
  name: '',
  code: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  trackingUrlTemplate: '',
  supportedCountries: '',
  serviceOptions: '',
  isActive: true
});

const carrierRules = {
  name: [
    { required: true, message: '请输入承运商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入承运商代码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 计算物流单过滤结果
const filteredShipments = computed(() => {
  if (loading.value) return [];
  
  return shipments.value.filter(shipment => {
    // 搜索过滤
    if (shipmentSearch.value && 
        !shipment.trackingNumber.includes(shipmentSearch.value) && 
        !shipment.orderId.includes(shipmentSearch.value)) {
      return false;
    }
    
    // 状态过滤
    if (shipmentStatusFilter.value && shipment.status !== shipmentStatusFilter.value) {
      return false;
    }
    
    // 承运商过滤
    if (carrierFilter.value && shipment.carrierName !== carrierFilter.value) {
      return false;
    }
    
    // 日期过滤
    if (shipmentDateRange.value && shipmentDateRange.value[0] && shipmentDateRange.value[1]) {
      const shipmentDate = new Date(shipment.shippingDate);
      const startDate = new Date(shipmentDateRange.value[0]);
      const endDate = new Date(shipmentDateRange.value[1]);
      
      if (!shipment.shippingDate || shipmentDate < startDate || shipmentDate > endDate) {
        return false;
      }
    }
    
    return true;
  });
});

// 获取物流状态类型
const getShipmentStatusType = (status) => {
  const statusMap = {
    'PENDING': 'info',
    'PROCESSING': 'warning',
    'SHIPPED': 'primary',
    'IN_TRANSIT': 'warning',
    'OUT_FOR_DELIVERY': 'success',
    'DELIVERED': 'success',
    'EXCEPTION': 'danger',
    'RETURNED': 'danger',
    'CANCELLED': 'info'
  };
  return statusMap[status] || 'info';
};

// 获取中文物流状态
const getChineseShipmentStatus = (status) => {
  const statusMap = {
    'PENDING': '待处理',
    'PROCESSING': '处理中',
    'SHIPPED': '已发货',
    'IN_TRANSIT': '运输中',
    'OUT_FOR_DELIVERY': '派送中',
    'DELIVERED': '已送达',
    'EXCEPTION': '异常',
    'RETURNED': '已退回',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchShipments();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchShipments();
};

// 获取物流单数据
const fetchShipments = async () => {
  loading.value = true;
  try {
    const response = await logisticsApi.getAllShipments();
    if (response && response.code === 200) {
      shipments.value = response.data;
      totalShipments.value = response.data.length;
    } else {
      ElMessage.error('获取物流单数据失败');
    }
  } catch (error) {
    console.error('获取物流单数据错误:', error);
    ElMessage.error('获取物流单数据出错');
  } finally {
    loading.value = false;
  }
};

// 获取承运商数据
const fetchCarriers = async () => {
  loading.value = true;
  try {
    const response = await logisticsApi.getAllCarriers();
    if (response && response.code === 200) {
      carriers.value = response.data;
    } else {
      ElMessage.error('获取承运商数据失败');
    }
  } catch (error) {
    console.error('获取承运商数据错误:', error);
    ElMessage.error('获取承运商数据出错');
  } finally {
    loading.value = false;
  }
};

// 显示物流单详情
const viewShipmentDetail = (shipment) => {
  currentShipment.value = shipment;
  shipmentDetailDialogVisible.value = true;
};

// 更新物流状态对话框
const updateShipmentStatus = (shipment) => {
  currentShipment.value = shipment;
  statusForm.status = '';
  statusForm.shippingDate = null;
  statusForm.deliveryDate = null;
  updateStatusDialogVisible.value = true;
};

// 提交物流状态更新
const submitStatusUpdate = async () => {
  if (!statusForm.status) {
    ElMessage.warning('请选择新的物流状态');
    return;
  }
  
  submitting.value = true;
  try {
    let response;
    
    if (statusForm.status === 'SHIPPED' && statusForm.shippingDate) {
      response = await logisticsApi.markShipmentAsShipped(currentShipment.value.id, statusForm.shippingDate);
    } else if (statusForm.status === 'DELIVERED' && statusForm.deliveryDate) {
      response = await logisticsApi.markShipmentAsDelivered(currentShipment.value.id, statusForm.deliveryDate);
    } else {
      response = await logisticsApi.updateShipmentStatus(currentShipment.value.id, statusForm.status);
    }
    
    if (response && response.code === 200) {
      ElMessage.success('物流状态更新成功');
      updateStatusDialogVisible.value = false;
      fetchShipments();
    } else {
      ElMessage.error('物流状态更新失败');
    }
  } catch (error) {
    console.error('更新物流状态错误:', error);
    ElMessage.error('更新物流状态出错');
  } finally {
    submitting.value = false;
  }
};

// 显示承运商表单对话框
const showCarrierDialog = (carrier) => {
  if (carrier) {
    // 编辑模式
    isEdit.value = true;
    Object.keys(carrierForm).forEach(key => {
      carrierForm[key] = carrier[key];
    });
  } else {
    // 新增模式
    isEdit.value = false;
    Object.keys(carrierForm).forEach(key => {
      if (key === 'isActive') {
        carrierForm[key] = true;
      } else {
        carrierForm[key] = '';
      }
    });
  }
  carrierDialogVisible.value = true;
};

// 提交承运商表单
const submitCarrierForm = async () => {
  const carrierFormRef = ref(null);
  
  if (!carrierFormRef.value) return;
  
  carrierFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        let response;
        if (isEdit.value) {
          // 更新承运商
          response = await logisticsApi.updateCarrier(carrierForm.id, carrierForm);
        } else {
          // 创建承运商
          response = await logisticsApi.createCarrier(carrierForm);
        }
        
        if (response && response.code === 200) {
          ElMessage.success(isEdit.value ? '承运商更新成功' : '承运商添加成功');
          carrierDialogVisible.value = false;
          fetchCarriers();
        } else {
          ElMessage.error(isEdit.value ? '承运商更新失败' : '承运商添加失败');
        }
      } catch (error) {
        console.error('提交承运商表单错误:', error);
        ElMessage.error('提交承运商表单出错');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 切换承运商状态
const toggleCarrierStatus = async (carrier) => {
  try {
    const response = await logisticsApi.toggleCarrierStatus(carrier.id, !carrier.isActive);
    
    if (response && response.code === 200) {
      ElMessage.success(`承运商状态已${!carrier.isActive ? '启用' : '禁用'}`);
      fetchCarriers();
    } else {
      ElMessage.error('更新承运商状态失败');
    }
  } catch (error) {
    console.error('更新承运商状态错误:', error);
    ElMessage.error('更新承运商状态出错');
  }
};

// 删除承运商
const deleteCarrier = async (carrier) => {
  if (carrier.isActive) {
    ElMessage.warning('无法删除启用状态的承运商，请先禁用');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除承运商 "${carrier.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await logisticsApi.deleteCarrier(carrier.id);
    
    if (response && response.code === 200) {
      ElMessage.success('承运商删除成功');
      fetchCarriers();
    } else {
      ElMessage.error('承运商删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除承运商错误:', error);
      ElMessage.error('删除承运商出错');
    }
  }
};

onMounted(() => {
  fetchShipments();
  fetchCarriers();
});
</script>

<style scoped>
.logistics-container {
  padding: 0;
  background-color: #f5f7fa;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
}

.page-title:after {
  content: '';
  display: block;
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #67C23A;
}

.logistics-tabs {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-bar, .action-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 250px;
}

.date-picker {
  width: 350px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.tracking-number {
  color: #409EFF;
  cursor: pointer;
  font-weight: 500;
}

.tracking-number:hover {
  text-decoration: underline;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
  }
  
  .search-input, .date-picker {
    width: 100%;
  }
}
</style> 